package io.zhengsh.juc._1aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class ConditionTest {

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        new Thread(() -> {
            lock.lock();
            try {
                log.info(Thread.currentThread().getName() + "开始执行任务");
                condition.await();
                log.info(Thread.currentThread().getName() + "任务执行结束");
            } catch (Throwable e) { e.printStackTrace(); } finally { lock.unlock(); }
        }, "t1").start();
        new Thread(() -> {
            lock.lock();
            try {
                log.info(Thread.currentThread().getName() + "开始执行任务");
                TimeUnit.SECONDS.sleep(2);
                condition.signal();
                log.info(Thread.currentThread().getName() + "任务执行结束");
            } catch (Throwable e) { e.printStackTrace(); } finally { lock.unlock(); }
        }, "t2").start();
    }
}
